/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/7/15 14:44:18
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Web.Admin.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using static CoreCms.Net.Configuration.GlobalEnumVars;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 微信用户列表
    ///</summary>
    [Description("微信用户列表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsUserWeChatInfoController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ICoreCmsUserWeChatInfoServices _coreCmsUserWeChatInfoServices;

        /// <summary>
        /// 构造函数
        ///</summary>
        public CoreCmsUserWeChatInfoController(IWebHostEnvironment webHostEnvironment
            , ICoreCmsUserWeChatInfoServices coreCmsUserWeChatInfoServices
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _coreCmsUserWeChatInfoServices = coreCmsUserWeChatInfoServices;
        }

        #region 获取列表============================================================
        // POST: Api/CoreCmsUserWeChatInfo/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsUserWeChatInfo>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsUserWeChatInfo, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "type" => p => p.type,
                "userId" => p => p.userId,
                "openid" => p => p.openid,
                "sessionKey" => p => p.sessionKey,
                "unionId" => p => p.unionId,
                "avatar" => p => p.avatar,
                "nickName" => p => p.nickName,
                "gender" => p => p.gender,
                "language" => p => p.language,
                "city" => p => p.city,
                "province" => p => p.province,
                "country" => p => p.country,
                "countryCode" => p => p.countryCode,
                "mobile" => p => p.mobile,
                "createTime" => p => p.createTime,
                "updateTime" => p => p.updateTime,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //用户ID int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //第三方登录类型 int
            var type = Request.Form["type"].FirstOrDefault().ObjectToInt(0);
            if (type > 0)
            {
                where = where.And(p => p.type == type);
            }
            //关联用户表 int
            var userId = Request.Form["userId"].FirstOrDefault().ObjectToInt(0);
            if (userId > 0)
            {
                where = where.And(p => p.userId == userId);
            }
            //openId nvarchar
            var openid = Request.Form["openid"].FirstOrDefault();
            if (!string.IsNullOrEmpty(openid))
            {
                where = where.And(p => p.openid.Contains(openid));
            }
            //缓存key nvarchar
            var sessionKey = Request.Form["sessionKey"].FirstOrDefault();
            if (!string.IsNullOrEmpty(sessionKey))
            {
                where = where.And(p => p.sessionKey.Contains(sessionKey));
            }
            //unionid nvarchar
            var unionId = Request.Form["unionId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(unionId))
            {
                where = where.And(p => p.unionId.Contains(unionId));
            }
            //头像 nvarchar
            var avatar = Request.Form["avatar"].FirstOrDefault();
            if (!string.IsNullOrEmpty(avatar))
            {
                where = where.And(p => p.avatar.Contains(avatar));
            }
            //昵称 nvarchar
            var nickName = Request.Form["nickName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(nickName))
            {
                where = where.And(p => p.nickName.Contains(nickName));
            }
            //性别 int
            var gender = Request.Form["gender"].FirstOrDefault().ObjectToInt(0);
            if (gender > 0)
            {
                where = where.And(p => p.gender == gender);
            }
            //语言 nvarchar
            var language = Request.Form["language"].FirstOrDefault();
            if (!string.IsNullOrEmpty(language))
            {
                where = where.And(p => p.language.Contains(language));
            }
            //城市 nvarchar
            var city = Request.Form["city"].FirstOrDefault();
            if (!string.IsNullOrEmpty(city))
            {
                where = where.And(p => p.city.Contains(city));
            }
            //省 nvarchar
            var province = Request.Form["province"].FirstOrDefault();
            if (!string.IsNullOrEmpty(province))
            {
                where = where.And(p => p.province.Contains(province));
            }
            //国家 nvarchar
            var country = Request.Form["country"].FirstOrDefault();
            if (!string.IsNullOrEmpty(country))
            {
                where = where.And(p => p.country.Contains(country));
            }
            //手机号码国家编码 nvarchar
            var countryCode = Request.Form["countryCode"].FirstOrDefault();
            if (!string.IsNullOrEmpty(countryCode))
            {
                where = where.And(p => p.countryCode.Contains(countryCode));
            }
            //手机号码 nvarchar
            var mobile = Request.Form["mobile"].FirstOrDefault();
            if (!string.IsNullOrEmpty(mobile))
            {
                where = where.And(p => p.mobile.Contains(mobile));
            }
            //创建时间 datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //更新时间 datetime
            var updateTime = Request.Form["updateTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(updateTime))
            {
                if (updateTime.Contains("到"))
                {
                    var dts = updateTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.updateTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.updateTime < dtEnd);
                }
                else
                {
                    var dt = updateTime.ObjectToDate();
                    where = where.And(p => p.updateTime > dt);
                }
            }
            //获取数据
            var list = await _coreCmsUserWeChatInfoServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/CoreCmsUserWeChatInfo/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var userAccountTypes = EnumHelper.EnumToList<GlobalEnumVars.UserAccountTypes>();
            jm.data = new
            {
                userAccountTypes
            };

            return jm;
        }
        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsUserWeChatInfo/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsUserWeChatInfoServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

    }
}
